package com.artifex.mupdf.viewer;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.util.Log;
import android.util.LruCache;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.mlkit.nl.translate.Translation;
import com.google.mlkit.nl.translate.Translator;
import com.google.mlkit.nl.translate.TranslatorOptions;

import java.util.Locale;

public class TranslateCache extends LruCache<TranslatorOptions, Translator> {
    /**
     * @param maxSize for caches that do not override {@link #sizeOf}, this is
     *                the maximum number of entries in the cache. For all other caches,
     *                this is the maximum sum of the sizes of the entries in this cache.
     */
    public TranslateCache(int maxSize) {
        super(maxSize);
    }

    @Override
    public void entryRemoved(
            boolean evicted, TranslatorOptions key, Translator oldValue, Translator newValue) {
        Log.d("TranslateCache", "close:" + oldValue);
        oldValue.close();
    }

    @Override
    protected Translator create(TranslatorOptions key) {
        return Translation.getClient(key);
    }

    static TranslateCache cache;
    public static TranslateCache obtain() {
        if(cache == null) {
            cache = new TranslateCache(1);
        }
        return cache;
    }

    public static void makeSureTranslate(Context context, Uri uri, OnSuccessListener<String> onSuccess, OnFailureListener onFailure) {
        SharedPreferences prefs = context.getSharedPreferences(TTSDocument.base64(uri.toString()), Context.MODE_PRIVATE);

        String toLanguage = prefs.getString(SettingsItem.TYPE.TO.name(), null);
        if(toLanguage == null) {
            onSuccess.onSuccess("No target language");
            return;
        }

        String fromLanguage = prefs.getString(SettingsItem.TYPE.FROM.name(), Locale.ENGLISH.getLanguage());

        if (fromLanguage.equals(toLanguage)) {
            onSuccess.onSuccess("Target language is the same As source language");
        } else {
            TranslateCache.obtain().get(new TranslatorOptions.Builder()
                    .setSourceLanguage(fromLanguage)
                    .setTargetLanguage(toLanguage)
                    .build()).translate("Hello World!").addOnSuccessListener(onSuccess).addOnFailureListener(onFailure);
        }

    }
}